import { useEffect, useRef, useState } from "react";
import { Chart } from "@antv/g2";
import { Button, Space } from "antd";

let data = [
  { genre: "Sports", sold: 275, age: 1 },
  { genre: "Strategy", sold: 115, age: 1 },
  { genre: "Action", sold: 120, age: 1 },
  { genre: "Shooter", sold: 350, age: 1 },
  { genre: "Other", sold: 150, age: 1 },
];

let interval: any;
let chart: any;

const Applications = () => {
  const boxRef = useRef(null);
  const [count, setCount] = useState(1);

  const handleClick = () => {
    // 修改数据，然后重新渲染图表
    // interval.data([
    //   { genre: "Sports", sold: 275, age: 1 },
    //   { genre: "Strategy", sold: 115, age: 10 },
    //   { genre: "Action", sold: 120, age: 100 },
    //   { genre: "Shooter", sold: 350, age: 1 },
    //   { genre: "Other", sold: 150, age: 1 },
    // ]);
    interval.encode("y", "sold");

    // 重新渲染
    chart.render();
  };

  useEffect(() => {
    // 实例化
    chart = new Chart({
      container: boxRef.current as unknown as HTMLElement,
    });

    // 声明可视化
    interval = chart
      .interval() // 创建一个 Interval 标记
      .data(data) // 绑定数据
      .transform({ type: "stackY" })
      .encode("x", "genre") // 编码 x 通道
      .encode("y", "age") // 编码 y 通道
      .encode("color", "genre")
      .scale("color", {
        range: ["red", "green", "blue", "#e8a838", "#61cdbb"],
      });

    // 渲染可视化
    chart.render();
  }, []);

  return (
    <div>
      <h1>应用</h1>
      <Space>
        <Button onClick={() => setCount((state) => state + 1)}>{count}</Button>

        <Button onClick={handleClick}>修改数据</Button>
      </Space>

      {/* 容器 */}
      <div className="box" ref={boxRef}></div>
    </div>
  );
};

export default Applications;
